<template>
	<view class="content">
		<!-- 收货方式切换 -->
		<!-- <view class="delivery-methods">
			<view v-for="(item, index) in items" :key="index" class="delivery-option" :class="{
										'selected': current === index,
										'first-item': index === 0,
										'last-item': index === items.length - 1
									}" @click="onClickItem(index)">
				<text>{{ item }}</text>
			</view>
		</view> -->
		<!-- 收货人信息 -->
		<view class="receiver-info">
			<view class="info-line">
				<text>{{ addressList.receivingName }} - {{ addressList.receivingPhoneNumber }}</text>
			</view>
			<view class="info-line address">
				<text>{{ addressList.provinceName }}{{ addressList.cityName }}{{ addressList.districtName }}{{ addressList.detailedAddress }}</text>
			</view>
			<uni-icons class="rightIcon" type="right" size="40" @click="select()"></uni-icons>
		</view>

		<!-- 商品信息 -->
		<block v-if="cartItems && cartItems.length">
			<view class="product-info" v-for="(item, index) in cartItems" :key="index">
				<image :src="getProductImageUrl(item)" class="product-image"></image>
				<view class="product-details">
					<view class="product-name">{{ getProductTitle(item) }}</view>
					<view class="product-quantity">×{{ item.count || 1 }}</view>
					<view class="product-specification">{{ getProductSpecifications(item) }}</view>
					<view class="product-price">￥{{ getProductPrice(item) }}</view>
				</view>
			</view>
		</block>

		<!-- 订单备注 -->
		<view class="order-note">
			备注说明
			<textarea class="textarea" v-model="orderNote" placeholder="请输入订单备注..." />
		</view>

		<!-- 运费和合计 -->
		<view class="total-section">
			<view class="postage">运费</view>
			<view class="total-price" style="color: #FF5B13;">￥{{ postage }}</view>
			<view class="postage">优惠金额</view>
			<view class="total-price" style="color: #FF5B13;">￥{{ discountAmount }}</view>
			<view class="postage">合计</view>
			<view class="total-price" style="color: #FF5B13;">￥{{ preferentialPrice }}</view>
		</view>

		<view class="footer-bar">
			<view class="total-price">合计：<text style="font-size: 42rpx;">￥{{ preferentialPrice }}</text></view>
			<view @click="showPaymentPopup" class="buy-now-btn">立即购买</view>
		</view>

		<!-- 支付方式选择弹出层 -->
		<uni-popup ref="paymentPopup">
			<view class="popup-content">
				<p class="title">支付方式</p>
				<view class="payment-option" @click="selectPaymentMethod(0)">
					<view class="icon-container">
						<image src="@/static/myImages/wx.png" class="icon"></image>
					</view>
					<view class="option-details">
						<view class="option-title">微信支付</view>
						<view class="option-description">使用微信快捷支付</view>
					</view>
				</view>
				<view class="divider"></view>
				<view class="payment-option" @click="selectPaymentMethod(2)">
					<view class="icon-container">
						<image src="@/static/myImages/yePay.png" class="icon"></image>
					</view>
					<view class="option-details">
						<view class="option-title">余额支付</view>
						<view class="option-description">可用余额 <text style="color: #FF5B13;">￥{{userInfo.balance}}</text>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="popup02" type="center">
			<view class="noBuyCommodity">
				<p class="title">请输入邀请码绑定</p>
				<input class="tishi" v-model="userUnId" type="text" placeholder="请输入邀请码" />
				<view class="" style="display: flex;justify-content: center;">
					<view class="button01" @click="close02()">
						取消
					</view>
					<view class="button02" @click="bindUser()">
						绑定
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		checkLoginStatus
	} from '@/utils/auth';
	import {
		getGoodsDetail
	} from '@/api/goods.js';
	import {
		getShoppingIds,
		addOrder,
		getInvitationRecord,
		getOrderAmount
	} from '@/api/order.js';
	import {
		getAddressList,
		getAddressID
	} from '@/api/address.js';
	import {
		getUserInfo,
		invitationRecord
	} from '@/api/user.js';
	import wx from 'jweixin-module';
	export default {
		data() {
			return {
				cartItems: [], // 存储购物车或单个商品详情
				items: ['快递配送', '到店自提'],
				current: 0,
				addressList: {},
				productQuantity: 1,
				orderNote: '',
				postage: 0.00,
				preferentialPrice: 0.00,
				discountAmount: 0.00,
				showPaymentOptions: false,
				selectedPayType: 0, // 默认为微信支付
				orderType: '', // 订单类型
				addressId: '',
				selectedMethod: 0, // 默认选中微信支付
				userInfo: {},
				userUnId: ''
			};
		},
		onLoad(options) {
			if (!checkLoginStatus()) {
				// 用户未登录，已重定向到登录页面
				console.log("未登录，跳转到登录");
				return;
			}
			this.orderType = options.type; // 在页面加载时保存订单类型
			// 根据传入的参数加载购物车或商品详情的数据
			if (options.type === '购物车') {
				try {
					const selectedIds = JSON.parse(decodeURIComponent(options.selectedIds));
					const idsString = selectedIds.join(',');
					this.getShopping(idsString);
				} catch (error) {
					console.error('Failed to parse selectedIds:', error);
				}
			} else if (options.type === '商品') {
				this.getDetail(options.goodsId, options.specId, options.specValueId, options.count);
			}
		},
		created() {
			uni.$on('addressSelected', this.onAddressSelected);
		},
		beforeDestroy() {
			uni.$off('addressSelected', this.onAddressSelected);
		},
		onShow() {
			this.getUser()
			this.getAddress();
		},
		methods: {
			//没有推广人· 就绑定
			bindUser() {
				const data = {
					launchCustomerUserId: null,
					userUnId: this.userUnId,
					userId: this.userInfo.id
				};
				invitationRecord(data).then(res => {
					if (res.data.code == 200) {
						uni.showToast({
							icon: 'none',
							title: '绑定成功',
						});
						this.$refs.popup02.close()
						this.getUser()
					}
				})
			},
			//获取用户信息
			getUser() {
				getUserInfo().then(res => {
					this.userInfo = res.data
				});
			},
			onAddressSelected(data) {
				// 处理接收到的地址信息
				console.log('Selected Address:', data);
				this.addressId = data.addressId
				this.getAddress()
				// 更新页面上的地址显示等操作
			},
			select() {
				uni.navigateTo({
					url: `/pages/my/address/index?selectAddr=true`
				});
			},
			getAddress() {
				// 获取用户地址列表
				if (this.addressId) {
					console.log("根据id查")
					getAddressID(this.addressId).then(res => {
						this.addressList = res.data
					});
				} else {
					console.log("根据默认查")
					const params = {
						// state: 1,
						pageSize: 99,
						pageNumber: 1
					};
					getAddressList(params).then(res => {
						let found = false;
						let selectedAddress;

						// 遍历 res.data.records 查找 state == 1 的地址
						for (let record of res.data.records) {
							if (record.state === 1) {
								selectedAddress = record;
								found = true;
								break; // 找到后跳出循环
							}
						}

						// 如果没有找到 state == 1 的地址，尝试取第一条记录
						if (!found && res.data.records.length > 0) {
							selectedAddress = res.data.records[0];
						}

						// 将选中的地址赋值给 this.addressList
						this.addressList = selectedAddress;

						console.log(this.addressList, "this.addressList");

						// 如果没有任何地址，执行页面跳转
						if (!this.addressList) {
							setTimeout(() => {
								uni.navigateTo({
									url: `/pages/my/address/index`
								});
							}, 200); // 3000 毫秒 = 3 秒的延迟
						}
					}).catch(err => {
						console.error("Failed to get address list:", err);
						// 处理错误情况，如显示错误信息或跳转到错误页面
					});
				}
			},
			onClickItem(index) {
				// 切换收货方式
				if (this.current !== index) {
					this.current = index;
				}
			},
			getShopping(ids) {
				// 获取购物车商品数据
				getShoppingIds(ids).then(res => {
					// 假设 this.cartItems 是从服务器响应中解析得到的商品项数组
					this.cartItems = this.parseCartItems(res.data);
					console.log(this.cartItems, "1111111111111111");

					// 初始化 vos 数组来存储多个 vos 对象
					let vos = [];

					// 遍历 cartItems 数组，为每个商品项创建一个对应的 vos 对象
					this.cartItems.forEach(item => {
						// 检查 item 中是否包含预期的结构，以避免潜在的运行时错误
						if (item.commoditySpecificationBasicInformationDto &&
							item.commoditySpecificationBasicInformationDto
							.commoditySpecificationAttributeInfoDto &&
							typeof item.count !== 'undefined') {
							vos.push({
								specificationId: item.commoditySpecificationBasicInformationDto
									.commoditySpecificationAttributeInfoDto.id,
								buyCount: item.count
							});
						}
					});

					console.log(vos, "vosvosvosvosvos");
					this.getOrderAmountList(vos)
				}).catch(error => {
					console.error('Failed to fetch shopping cart items:', error);
				});
			},
			getDetail(goodsId, specId, specValueId, count) {
				// 获取商品详情
				getGoodsDetail(goodsId).then(res => {
					const parsedItem = this.parseProductDetail(res.data, specId, specValueId, count);
					this.cartItems = parsedItem;
					const vos = this.cartItems.map(item => ({
						specificationId: specValueId,
						buyCount: count
					}));
					this.getOrderAmountList(vos)
				}).catch(error => {
					console.error('Failed to fetch goods detail:', error);
				});
			},
			getOrderAmountList(vos) {
				getOrderAmount(vos).then(res => {
					this.postage = res.data.postage
					this.preferentialPrice = res.data.preferentialPrice
					this.discountAmount = res.data.discountAmount
				})
			},
			parseCartItems(cartData) {
				// 解析购物车数据
				return cartData.map(item => ({
					count: item.count,
					commodityDto: item.commodityDto || {},
					commoditySpecificationBasicInformationDto: item
						.commoditySpecificationBasicInformationDto || {},
					specAttrInfo: item.commoditySpecificationBasicInformationDto
						?.commoditySpecificationAttributeInfoDto || {}
				}));
			},
			parseProductDetail(detail, specId, specValueId, count) {
				// 解析商品详情数据
				const specBasicInfo = detail.commoditySpecificationBasicInformationDtoS.find(basicSpec =>
					basicSpec.id === parseInt(specId));
				const specAttrInfo = specBasicInfo?.commoditySpecificationAttributeInfoDtoS?.find(attrSpec =>
					attrSpec.id === parseInt(specValueId));

				return [{
					count: parseInt(count),
					commodityDto: detail,
					commoditySpecificationBasicInformationDto: specBasicInfo,
					specAttrInfo: specAttrInfo
				}];
			},
			// 显示支付方式选择弹出层
			showPaymentPopup() {
				if (this.userInfo.puser) {
					this.$refs.paymentPopup.open();
				} else {
					this.$refs.popup02.open();
				}
			},
			close02() {
				this.$refs.popup02.close()
			},
			selectPaymentMethod(payType) {
				this.selectedPayType = payType;
				this.$refs.paymentPopup.close(); // 关闭弹出层
				this.submitSelectedOrder();
			},
			submitSelectedOrder() {
				const purchaseInformationVos = this.cartItems.map(item => ({
					specificationId: item.specAttrInfo?.id || '', // 规格ID
					buyCount: item.count || 1 // 购买数量
				}));

				// 根据之前保存的 orderType 来确定基础支付类型
				let basePayType = this.orderType === '购物车' ? 1 : 0;
				basePayType += this.selectedPayType;

				if (basePayType == 2 || basePayType == 3) {
					const data = {
						payType: basePayType.toString(), // 将支付类型转换为字符串
						purchaseInformationVos: purchaseInformationVos,
						siteId: this.addressList.id,
						userRemarks: this.orderNote
					};
					addOrder(data).then(res => {
						console.log(res, "余额支付")
						if (res.code == 200) {
							uni.showToast({
								icon: 'none',
								title: '支付成功',
							});
							uni.redirectTo({
								url: '/pages/my/myOrder/index'
							})
						} else {
							uni.showToast({
								icon: 'none',
								title: res.data
							});
						}
					}).catch(error => {
						console.error('Failed to submit order:', error);
					});
				} else {
					const data = {
						payType: basePayType.toString(), // 将支付类型转换为字符串
						purchaseInformationVos: purchaseInformationVos,
						siteId: this.addressList.id,
						userRemarks: this.orderNote,
						tradeType: 1
					};
					// 假设 addOrder 是一个异步函数，用于创建订单并获取支付参数
					addOrder(data).then(res => {
						console.log(res, "微信支付");

						// 检查 WeixinJSBridge 是否可用
						if (typeof WeixinJSBridge === "undefined") {
							console.error(
								"WeixinJSBridge is not available. Please open this page in WeChat browser.");
							uni.showToast({
								title: '请在微信浏览器中打开此页面',
								icon: 'none',
								duration: 2000
							});
							return;
						}

						// 调用 WeixinJSBridge 进行支付
						WeixinJSBridge.invoke(
							'getBrandWCPayRequest', {
								appId: res.data.appId,
								timeStamp: "" + res.data.timeStamp, // 强制转换为字符串
								nonceStr: res.data.nonceStr,
								package: res.data.packageValue,
								signType: res.data.signType,
								paySign: res.data.paySign
							},
							function(response) {
								console.log(response, "支付回调结果");
								handlePaymentResponse(response);
							}
						);
					}).catch(error => {
						console.error("创建订单失败：", error);
						uni.showToast({
							title: '创建订单失败，请稍后再试',
							icon: 'none',
							duration: 2000
						});
					});

					// 定义处理支付响应的函数
					function handlePaymentResponse(response) {
						if (response.err_msg === "get_brand_wcpay_request:ok") {
							// 支付成功后的处理逻辑
							console.log("支付成功！");
							uni.showToast({
								title: '支付成功',
								icon: 'success',
								duration: 2000
							});
							// 可以在这里添加更多支付成功的逻辑，例如跳转到订单详情页等
							uni.redirectTo({
								url: '/pages/my/myOrder/index'
							})
						} else {
							// 支付失败或其他情况的处理逻辑
							console.error("支付失败或用户取消支付：", response.err_msg);
							uni.showToast({
								title: '支付失败或已取消',
								icon: 'none',
								duration: 2000
							});

							// 根据需要可以提供给用户重新尝试支付的机会
						}
					}
				}
				console.log('Submit Order with Data:', data);
			},
			getProductImageUrl(item) {
				// 获取商品图片URL
				return item.commodityDto?.pictureIntegrationDtoS && item.commodityDto?.pictureIntegrationDtoS[0] ?
					item
					.commodityDto.pictureIntegrationDtoS[0].pictureUrl : '';
			},
			getProductTitle(item) {
				// 获取商品标题
				return item.commodityDto?.commodityName || '';
			},
			hasValidSpecification(specAttrInfo) {
				return specAttrInfo.specificationName && specAttrInfo.specificationValue &&
					specAttrInfo.specificationName !== '' && specAttrInfo.specificationValue !== '';
			},
			getProductSpecifications(item) {
				// 获取商品规格信息
				const specBasicInfo = item.commoditySpecificationBasicInformationDto || {};
				const specAttrInfo = item.specAttrInfo || {};

				// 构建基础的标签文本
				let tagsText = `${specBasicInfo.attributeName || ''}: ${specBasicInfo.attributeValue || ''}`;

				// 如果 specificationName 和 specificationValue 都有效，则追加到标签文本
				if (this.hasValidSpecification(specAttrInfo)) {
					tagsText += `, ${specAttrInfo.specificationName}: ${specAttrInfo.specificationValue}`;
				}

				return tagsText;
			},
			getProductPrice(item) {
				// 获取商品价格
				return item.specAttrInfo ? item.specAttrInfo.sellingPrice : 0;
			}
		},
	};
</script>

<style lang="scss">
	@import '@/uni.scss'; // 导入全局 SCSS 变量文件

	.content {
		min-height: 100vh;
		padding: 20rpx;
		background-color: $uni-bg-color-grey;
	}

	.delivery-methods {
		display: flex;
		margin-bottom: 20rpx;

		.delivery-option {
			flex-grow: 1;
			text-align: center;
			padding: 10rpx;
			cursor: pointer;
			transition: background-color 0.3s, color 0.3s;
			border-radius: 0; // 默认没有圆角

			&.selected {
				background-color: #FF5B13;
				color: #fff;
			}

			&:not(.selected) {
				background-color: #fff;
				color: #000;
			}

			&.first-item {
				border-top-left-radius: 40rpx;
				border-bottom-left-radius: 40rpx;
			}

			&.last-item {
				border-top-right-radius: 40rpx;
				border-bottom-right-radius: 40rpx;
			}
		}
	}

	.receiver-info {
		background-color: #fff;
		padding: 20rpx;
		margin-bottom: 20rpx;
		border-radius: 20rpx;
		font-size: 28rpx;

		.info-line {
			margin-bottom: 10rpx;

			&.address {
				word-break: break-all;
			}
		}

		.rightIcon {
			float: right;
			margin-top: -88rpx;
		}
	}

	.product-info {
		display: flex;
		align-items: center;
		background-color: #fff;
		padding: 20rpx;
		margin-bottom: 20rpx;
		border-radius: 20rpx;
		font-size: 28rpx;

		.product-image {
			width: 160rpx;
			height: 160rpx;
			margin-right: 20rpx;
		}

		.product-details {
			width: 70%;
			display: flex;
			flex-wrap: wrap;

			.product-name {
				width: 80%;
				font-size: 32rpx;
				margin-bottom: 10rpx;
				font-weight: bold;
			}

			.product-quantity {
				width: 20%;
				color: #666;
				text-align: right;
				margin-bottom: 10rpx;
			}

			.product-specification {
				width: 100%;
				color: #666;
				margin-bottom: 10rpx;
			}

			.product-price {
				width: 100%;
				color: $uni-color-orange;
				margin-bottom: 10rpx;
			}
		}
	}

	.order-note {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		font-weight: bold;
		font-size: 28rpx;

		.textarea {
			width: 94%;
			background-color: #f8f8f8;
			padding: 20rpx;
			margin-top: 10rpx;
			height: 200rpx;
			font-weight: 100;
		}
	}

	.total-section {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		display: flex;
		flex-wrap: wrap;
		font-size: 28rpx;

		.postage {
			width: 50%;
			margin-bottom: 10rpx;
		}

		.total-price {
			width: 50%;
			text-align: right;
			margin-bottom: 10rpx;
		}
	}



	.footer-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 20rpx;
		box-shadow: 0 -2px 10rpx rgba(0, 0, 0, 0.1);

		.total-price {
			width: 60%;
		}

		.buy-now-btn {
			width: 40%;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-radius: 80rpx;
			background-color: $uni-color-orange;
			color: #fff;
		}
	}

	.popup-content {
		background-color: $uni-bg-color-white;
		width: 500rpx;
		border-radius: 8rpx;
		padding: 40rpx 30rpx;
		text-align: center;
		margin-top: -200rpx;

		view {
			text-align: left;
		}

		.title {
			text-align: center;
			margin-bottom: 30rpx;
		}
	}

	.noBuyCommodity {
		width: 466rpx;
		height: 324rpx;
		background: linear-gradient(to bottom, #FFD1AB, #FFF0D6);
		border-radius: 20rpx;
		padding: 20rpx;

		.title {
			font-weight: bold;
			font-size: 30rpx;
			color: #333333;
			line-height: 34rpx;
			text-align: center;
			margin: 30rpx;
		}

		.tishi {
			height: 60rpx;
			line-height: 60rpx;
			font-size: 30rpx;
			font-weight: 400;
			border-radius: 10rpx;
			background-color: #fff;
			color: #333333;
			text-align: left;
			margin: 40rpx 80rpx;
		}

		.button01 {
			width: 177rpx;
			height: 62rpx;
			border-radius: 10rpx;
			border: 2rpx solid #FF5B13;
			font-weight: 400;
			font-size: 26rpx;
			color: #FF5B13;
			text-align: center;
			line-height: 62rpx;
			margin-right: 20rpx;
		}

		.button02 {
			width: 177rpx;
			height: 62rpx;
			background: #FF5B13;
			border-radius: 10rpx;
			font-weight: 400;
			font-size: 26rpx;
			color: #FFFFFF;
			text-align: center;
			line-height: 62rpx;
		}
	}

	.payment-option {
		display: flex;
		align-items: center;
		padding: 10rpx 0;
		cursor: pointer;

		.icon-container {
			flex: 0 0 auto;
			margin-right: 20rpx;

			.icon {
				width: 40rpx;
				height: 40rpx;
			}
		}

		.option-details {
			flex: 1 1 auto;

			.option-title {
				font-size: 32rpx;
				margin-bottom: 5rpx;
			}

			.option-description {
				font-size: 28rpx;
				color: $uni-text-color-grey6;
			}
		}
	}

	.divider {
		height: 1px;
		background-color: $uni-border-color;
		margin: 10rpx 0;
	}
</style>